package com.ruoyi.fangyuan.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: DataSourceConfig
 * @Description:
 * @Auther: 龙天
 * @Version: 1.0
 * @create 2023/5/5 15:10
 */
@Profile("dev") // 开发模式配置文件
@Configuration
@MapperScan(basePackages = "com.ruoyi.fangyuan.mapper")
public class DataSourceConfig {
    /**
     * 加载主数据源
     * @return
     */
    @Bean("masterDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource () {
        return DataSourceBuilder.create().build();
    }

    /**
     * 加载从数据源
     * @return
     */
    @Bean("slaveDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource () {
        return DataSourceBuilder.create().build();
    }

    /**
     * 将多个数据源都加载到AstractRoutingDataSource中的map
     * @param masterDataSource
     * @param slaveDataSource
     * @return
     */
    @Bean("targetDataSource")
    public DataSource myRoutingDataSource (
            @Qualifier("masterDataSource") DataSource masterDataSource,
            @Qualifier("slaveDataSource") DataSource slaveDataSource
    ) {
        Map<Object, Object> map = new HashMap<>();
        map.put(DBTypeEnum.MASTER, masterDataSource);
        map.put(DBTypeEnum.SLAVE, slaveDataSource);
        RoutingDataSource source = new RoutingDataSource();
        source.setDefaultTargetDataSource(masterDataSource); // 设置默认数据源
        source.setTargetDataSources(map); // 设置路由表，使用map的key，value方式得到对应的数据源
        return source;
    }

}
